package com.lifeverse.service;

import com.lifeverse.entity.Decision;
import com.lifeverse.entity.DecisionFeedback;
import com.lifeverse.entity.DecisionHistory;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.DecisionStatus;
import com.lifeverse.entity.enums.DecisionType;
import com.lifeverse.repository.DecisionFeedbackRepository;
import com.lifeverse.repository.DecisionHistoryRepository;
import com.lifeverse.repository.DecisionRepository;
import com.lifeverse.repository.LifeEntityRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 决策服务
 * 提供决策管理的业务逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DecisionService {
    
    private final DecisionRepository decisionRepository;
    private final DecisionHistoryRepository decisionHistoryRepository;
    private final DecisionFeedbackRepository decisionFeedbackRepository;
    private final LifeEntityRepository lifeEntityRepository;
    private final DecisionEngine decisionEngine;
    
    /**
     * 创建决策
     */
    @Transactional
    public Decision createDecision(Long lifeEntityId, DecisionType type, String title, 
                                 String description, Map<String, Object> context) {
        log.info("创建决策 - 生命体ID: {}, 类型: {}, 标题: {}", lifeEntityId, type, title);
        
        LifeEntity lifeEntity = lifeEntityRepository.findById(lifeEntityId)
                .orElseThrow(() -> new RuntimeException("生命体不存在: " + lifeEntityId));
        
        return decisionEngine.createDecision(lifeEntity, type, title, description, context);
    }
    
    /**
     * 处理决策
     */
    public CompletableFuture<Decision> processDecision(Long decisionId) {
        log.info("处理决策 - ID: {}", decisionId);
        return decisionEngine.processDecision(decisionId);
    }
    
    /**
     * 执行决策
     */
    public CompletableFuture<Decision> executeDecision(Long decisionId) {
        log.info("执行决策 - ID: {}", decisionId);
        return decisionEngine.executeDecision(decisionId);
    }
    
    /**
     * 获取决策详情
     */
    public Decision getDecision(Long decisionId) {
        return decisionRepository.findById(decisionId)
                .orElseThrow(() -> new RuntimeException("决策不存在: " + decisionId));
    }
    
    /**
     * 获取生命体的决策列表
     */
    public Page<Decision> getDecisionsByLifeEntity(Long lifeEntityId, Pageable pageable) {
        LifeEntity lifeEntity = lifeEntityRepository.findById(lifeEntityId)
                .orElseThrow(() -> new RuntimeException("生命体不存在: " + lifeEntityId));
        
        return decisionRepository.findByLifeEntity(lifeEntity, pageable);
    }
    
    /**
     * 获取特定状态的决策列表
     */
    public Page<Decision> getDecisionsByStatus(Long lifeEntityId, DecisionStatus status, Pageable pageable) {
        LifeEntity lifeEntity = lifeEntityRepository.findById(lifeEntityId)
                .orElseThrow(() -> new RuntimeException("生命体不存在: " + lifeEntityId));
        
        return decisionRepository.findByLifeEntityAndStatus(lifeEntity, status, pageable);
    }
    
    /**
     * 获取决策历史
     */
    public Page<DecisionHistory> getDecisionHistory(Long decisionId, Pageable pageable) {
        Decision decision = getDecision(decisionId);
        return decisionHistoryRepository.findByDecision(decision, pageable);
    }
    
    /**
     * 获取决策反馈
     */
    public Page<DecisionFeedback> getDecisionFeedback(Long decisionId, Pageable pageable) {
        Decision decision = getDecision(decisionId);
        return decisionFeedbackRepository.findByDecision(decision, pageable);
    }
    
    /**
     * 添加决策反馈
     */
    @Transactional
    public DecisionFeedback addDecisionFeedback(Long decisionId, String feedbackType, String source,
                                              String content, BigDecimal rating, Boolean isPositive) {
        log.info("添加决策反馈 - 决策ID: {}, 类型: {}", decisionId, feedbackType);
        
        Decision decision = getDecision(decisionId);
        
        DecisionFeedback feedback = DecisionFeedback.create(decision, feedbackType, source, 
                                                          content, rating, isPositive);
        
        return decisionFeedbackRepository.save(feedback);
    }
    
    /**
     * 处理决策反馈
     */
    @Transactional
    public DecisionFeedback processFeedback(Long feedbackId, String processingResult) {
        log.info("处理决策反馈 - ID: {}", feedbackId);
        
        DecisionFeedback feedback = decisionFeedbackRepository.findById(feedbackId)
                .orElseThrow(() -> new RuntimeException("反馈不存在: " + feedbackId));
        
        feedback.markProcessed(processingResult);
        return decisionFeedbackRepository.save(feedback);
    }
    
    /**
     * 取消决策
     */
    @Transactional
    public Decision cancelDecision(Long decisionId, String reason) {
        log.info("取消决策 - ID: {}, 原因: {}", decisionId, reason);
        
        Decision decision = getDecision(decisionId);
        
        if (decision.getStatus().isCompleted()) {
            throw new RuntimeException("已完成的决策无法取消");
        }
        
        decision.setStatus(DecisionStatus.CANCELLED);
        Decision savedDecision = decisionRepository.save(decision);
        
        // 记录历史
        DecisionHistory history = DecisionHistory.create(decision, "CANCEL", "决策取消: " + reason,
                                                        decision.getStatus().name(), DecisionStatus.CANCELLED.name(), "USER");
        decisionHistoryRepository.save(history);
        
        return savedDecision;
    }
    
    /**
     * 获取决策统计信息
     */
    public DecisionStatistics getDecisionStatistics(Long lifeEntityId) {
        LifeEntity lifeEntity = lifeEntityRepository.findById(lifeEntityId)
                .orElseThrow(() -> new RuntimeException("生命体不存在: " + lifeEntityId));
        
        DecisionStatistics stats = new DecisionStatistics();
        
        // 总决策数
        long totalDecisions = decisionRepository.countByLifeEntity(lifeEntity);
        stats.setTotalDecisions(totalDecisions);
        
        // 各状态决策数
        for (DecisionStatus status : DecisionStatus.values()) {
            long count = decisionRepository.countByLifeEntityAndStatus(lifeEntity, status);
            stats.getStatusCounts().put(status, count);
        }
        
        // 各类型决策数
        for (DecisionType type : DecisionType.values()) {
            long count = decisionRepository.countByLifeEntityAndType(lifeEntity, type);
            stats.getTypeCounts().put(type, count);
        }
        
        // 计算成功率
        long completedDecisions = decisionRepository.countByLifeEntityAndStatus(lifeEntity, DecisionStatus.COMPLETED);
        long failedDecisions = decisionRepository.countByLifeEntityAndStatus(lifeEntity, DecisionStatus.FAILED);
        
        if (completedDecisions + failedDecisions > 0) {
            double successRate = (double) completedDecisions / (completedDecisions + failedDecisions);
            stats.setSuccessRate(BigDecimal.valueOf(successRate));
        } else {
            stats.setSuccessRate(BigDecimal.ZERO);
        }
        
        return stats;
    }
    
    /**
     * 获取活跃决策
     */
    public List<Decision> getActiveDecisions() {
        List<DecisionStatus> activeStatuses = List.of(
                DecisionStatus.ANALYZING, 
                DecisionStatus.EVALUATING, 
                DecisionStatus.EXECUTING
        );
        return decisionRepository.findActiveDecisions(activeStatuses);
    }
    
    /**
     * 获取超时决策
     */
    public List<Decision> getTimeoutDecisions() {
        List<DecisionStatus> completedStatuses = List.of(
                DecisionStatus.COMPLETED, 
                DecisionStatus.CANCELLED, 
                DecisionStatus.FAILED
        );
        return decisionRepository.findTimeoutDecisions(LocalDateTime.now(), completedStatuses);
    }
    
    /**
     * 处理超时决策
     */
    @Transactional
    public void handleTimeoutDecisions() {
        List<Decision> timeoutDecisions = getTimeoutDecisions();
        
        for (Decision decision : timeoutDecisions) {
            log.warn("处理超时决策 - ID: {}, 标题: {}", decision.getId(), decision.getTitle());
            
            decision.setStatus(DecisionStatus.FAILED);
            decision.setReasoning((decision.getReasoning() != null ? decision.getReasoning() + "\n" : "") + 
                                "决策超时自动失败");
            
            decisionRepository.save(decision);
            
            // 记录历史
            DecisionHistory history = DecisionHistory.create(decision, "TIMEOUT", "决策超时",
                                                            decision.getStatus().name(), DecisionStatus.FAILED.name(), "SYSTEM");
            decisionHistoryRepository.save(history);
        }
    }
    
    /**
     * 获取未处理的反馈
     */
    public List<DecisionFeedback> getUnprocessedFeedback() {
        return decisionFeedbackRepository.findByIsProcessedFalse();
    }
    
    /**
     * 批量处理反馈
     */
    @Transactional
    public void processUnprocessedFeedback() {
        List<DecisionFeedback> unprocessedFeedback = getUnprocessedFeedback();
        
        for (DecisionFeedback feedback : unprocessedFeedback) {
            try {
                String result = "自动处理: ";
                
                if (feedback.isHighImpact()) {
                    result += "高影响反馈，需要关注";
                } else if (Boolean.TRUE.equals(feedback.getIsPositive())) {
                    result += "正面反馈，继续保持";
                } else {
                    result += "负面反馈，需要改进";
                }
                
                feedback.markProcessed(result);
                decisionFeedbackRepository.save(feedback);
                
                log.debug("自动处理反馈 - ID: {}", feedback.getId());
                
            } catch (Exception e) {
                log.error("处理反馈失败 - ID: {}", feedback.getId(), e);
            }
        }
    }
    
    // 内部类定义
    public static class DecisionStatistics {
        private long totalDecisions;
        private Map<DecisionStatus, Long> statusCounts = new HashMap<>();
        private Map<DecisionType, Long> typeCounts = new HashMap<>();
        private BigDecimal successRate;
        
        // getters and setters
        public long getTotalDecisions() { return totalDecisions; }
        public void setTotalDecisions(long totalDecisions) { this.totalDecisions = totalDecisions; }
        public Map<DecisionStatus, Long> getStatusCounts() { return statusCounts; }
        public void setStatusCounts(Map<DecisionStatus, Long> statusCounts) { this.statusCounts = statusCounts; }
        public Map<DecisionType, Long> getTypeCounts() { return typeCounts; }
        public void setTypeCounts(Map<DecisionType, Long> typeCounts) { this.typeCounts = typeCounts; }
        public BigDecimal getSuccessRate() { return successRate; }
        public void setSuccessRate(BigDecimal successRate) { this.successRate = successRate; }
    }
}